import { ref, shallowRef } from 'vue'

import { catchFn } from '@/libs/common'
import { getQuizResult } from '@/pages/quiz/api'
import { getCanvas, getCanvasImage, getImageInstance } from '@/components/OffScreenCanvas/data'
import { imagePathOnly } from '@/libs/file-utils'
import { userInfo } from '@/libs/user'
import { showGuideQuizMask } from './guide-quiz-mask/data'

/** 好友信息 */
const friendInfo = shallowRef<T_Friend>()
/** 好友合盘解读 */
const result = shallowRef<T_FortuneResult>()
/** 好友合盘解读 */
const fortuneReport = shallowRef<T_FortuneReport>()
/** 结果ID */
let resultId = 0
/** 是否生成报告中 */
const isCreating = ref(false)

/** 是否未解锁高级报告 */
const lockedStatus = shallowRef<{
  /** 提示文字 */
  itemId: number
  /** 提示文字 */
  tip: string
  /** 解锁价格 */
  price: number
}>()

const defaultFortuneList = [
  {
    key: 'love',
    title: '',
    shortTitle: '',
    desc: '',
    desc2: '',
  },
  {
    key: 'wealth',
    title: '',
    shortTitle: '',
    desc: '',
    desc2: '',
  },
  {
    key: 'career',
    title: '',
    shortTitle: '',
    desc: '',
    desc2: '',
  },
  {
    key: 'health',
    title: '',
    shortTitle: '',
    desc: '',
    desc2: '',
  },
]
const fortuneList = shallowRef<
  {
    key: T_FortuneType
    title: string
    shortTitle: string
    desc: string
  }[]
>(JSON.parse(JSON.stringify(defaultFortuneList)))

/** 合盘海报 */
const poster = ref<string>()

let lastType = 0
let lastFriendId = -1
let firstCreating = true

export {
  friendInfo,
  result,
  fortuneReport,
  resultId,
  isCreating,
  lockedStatus,
  fortuneList,
  poster,
}

/** 轮询函数 */
let queryFn: any = null

/**
 * 更新好友合盘解读
 * @param type 类型
 * @param friendId 好友ID
 */
const update = (type = lastType, friendId = lastFriendId) =>
  catchFn(
    async () => {
      queryFn = null
      lastType = type
      lastFriendId = friendId

      // loading(true)

      const { data } = await getQuizResult({
        typeCode: 'fortune',
        friendId,
        type,
      })

      data.userInfo.birthday = data.userInfo.birthday.replace(/-/g, '.')
      data.friend.birthday = data.friend.birthday.replace(/-/g, '.')

      // 未加载完成
      if (data.testStatus === 1) {
        if (firstCreating) {
          firstCreating = false
          showGuideQuizMask.value = true
        }

        isCreating.value = true
        queryFn = setTimeout(update, 2000)
        return
      } else isCreating.value = false

      friendInfo.value = data.friend
      result.value = data.fortuneResult
      fortuneReport.value = result.value?.mbtiReport || result.value?.baziReport
      userInfo.value = data.userInfo
      resultId = data.id
      lockedStatus.value = data.isLocked
        ? {
            itemId: data.unlockItemId,
            tip: data.unlockText,
            price: data.unlockItemPrice || 48,
          }
        : undefined

      fortuneList.value = fortuneList.value.map(item => {
        const tar = result.value?.[item.key]

        if (tar) {
          item.title = tar.title
          item.shortTitle = tar.shortTitle
          item.desc = tar.description
        }

        return item
      })
    },
    {
      disableLoading: true,
    },
  )

/**
 * 合成海报
 */
const createPoster = (type: string) =>
  catchFn(async () => {
    if (!result.value) throw '数据缺失'

    const { ctx } = await getCanvas()

    // 获取海报
    const img_poster = await getImageInstance(
      imagePathOnly(`community/friend/poster/bg-${type}.jpg`),
    )

    // 合成
    const w = img_poster.width
    const h = img_poster.height

    await getCanvas(w, h)

    // 1. 底图
    ctx.drawImage(img_poster, 0, 0, w, h)

    // 2. 姓名
    {
      const title = `${userInfo.value?.nickname || '游客'}&${friendInfo.value?.nickname || '朋友'}`

      ctx.font = '48px ChillRoundM'

      const test = ctx.measureText(title)
      const left = 375 - test.width / 2
      const top = ((type == '12' ? 142 : 179) + 32 - 8) * 2

      ctx.fillStyle = type == '12' ? '#fff' : '#0D0602'
      ctx.fillText(title, left, top)
    }

    // x. 水印
    // if (userInfo.value?.watermark) {
    //   const img_watermark = await getImageInstance(imagePathOnly('watermark.png'))

    //   for (let i = 0; i < 15; i++) {
    //     for (let j = 0; j < 2; j++) {
    //       ctx.fillStyle = '#ffffff55'
    //       ctx.drawImage(img_watermark, 440 * j + (i % 2 == 0 ? -50 : 170), 110 * i, 220, 100)
    //     }
    //   }
    // }

    // final. 导出
    poster.value = await getCanvasImage()

    // #ifdef WEB || APP
    uni.navigateTo({ url: '/pages/community/friend/report/poster' })
    // #endif
    // #ifdef MP-WEIXIN
    uni.showShareImageMenu({
      path: poster.value,
      // @ts-ignore
      entrancePath: '/pages/index/index',
    })
    // #endif
  })

/**
 * 绘制多行文字
 * @param ctx 画布
 * @param text 文字内容
 * @param x 坐标X
 * @param y 坐标Y
 */
// const drawText = (ctx: any, text: string, x: number, y: number) => {
//   const chars = text.split('')

//   // 逐行绘制
//   let line = ''

//   for (const ch of chars) {
//     const testLine = line + ch
//     const testWidth = ctx.measureText(testLine).width

//     if (testWidth > 216) {
//       ctx.fillText(line, x, y)
//       y += 30
//       line = ch
//     } else {
//       line = testLine
//     }
//   }

//   ctx.fillText(line, x, y)
// }

/**
 * 还原状态
 */
const clear = () => {
  lastType = 0
  lastFriendId = -1
  firstCreating = true
  friendInfo.value = undefined
  result.value = undefined
  fortuneList.value = JSON.parse(JSON.stringify(defaultFortuneList))

  isCreating.value = false

  if (queryFn) {
    clearTimeout(queryFn)
    queryFn = null
  }
}

export { update, createPoster, clear }
